//
//  MYGAnswerViewViewController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/4/2.
// 参考 MYGCommunityHomeController

import UIKit
import MJRefresh
import JXSegmentedView
import QMUIKit

class MYGAnswerViewViewController: MYGBaseController {
    
//    private var tags: [MYGCommunityTypeModel] = [] {
//        didSet {
//            dataSource.titles = tags.map{$0.name}
//           
//            segmentedView.reloadData()
//            tableView.reloadData()
//        }
//    }
    private var titles:[String] = []
    private var page = 0
    private var pageSize = 10
    private var listModels:  [MYGCommunityListModel] = []
    var filterType: MYGCommunityListFilterType = .listType(type: .question)
    private var filterTitle: String?
    var type =  0
    
    private var communities_id:Int = 0
    private var contents:[MYGCommunityTypeModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configUI()
        getCommunityType()
        
        NotificationCenter.default.addObserver(self, selector: #selector(reloadMyAnswerData), name: NSNotification.Name.init("reloadAnswerList"), object: nil)

    }
    
    // MARK: - UI
    private func configUI() {
        view.backgroundColor = .white
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: orderButton)
        
        title = "问问"
        view.addSubview(searchContentView)
        view.addSubview(segmentedView)
        view.addSubview(tableView)
        
        searchContentView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(25)
            make.top.equalToSuperview().offset(16)
            make.height.equalTo(28)
        }
        searchContentView.addSubviews([
            searchTextFiled,
        ])
        searchTextFiled.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(14)
            make.top.equalToSuperview()
            make.height.equalTo(28)
        }
        
        segmentedView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(searchContentView.snp.bottom)
            make.height.equalTo(47)
        }
        tableView.snp.makeConstraints { make in
            make.top.equalTo(segmentedView.snp.bottom).offset(10)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    private lazy var orderButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("我的回答", for: .normal)
        btn.setTitleColor(.rgba(69, 131, 250, 1), for: .normal)
        btn.titleLabel?.font = .regular(13)
        btn.addTarget(self, action: #selector(navigationMoreAction), for: .touchUpInside)
        return btn
    }()
    
    private func reloadListView() {
        let cellModels = listModels.map({ listModel in
            return MYGCommunityCellModel(with: listModel)
        })
        tableView.reload(with: cellModels)
    }
    
    private lazy var searchContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(243, 243, 243)
        view.layerCornerRadius = 14
        view.clipsToBounds = true
        return view
    }()
    
    private lazy var searchTextFiled: QMUITextField = {
        let tf = QMUITextField()
        tf.font = .regular(13)
        tf.textInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
        tf.clearButtonMode = .whileEditing
        let placeholderAtt = NSAttributedString(string: "输入想看的内容", attributes: [.foregroundColor: UIColor.rgba(124, 124, 124)]);
        tf.attributedPlaceholder = placeholderAtt;
        let leftImageView = UIImageView(image: UIImage(named: "Chat/search"))
        leftImageView.bounds = CGRect(x: 0, y: 0, width: 15, height: 15)
        tf.leftView = leftImageView
        tf.leftViewMode = .always
        tf.addTarget(self, action: #selector(textFiledEdtingEnded), for: .editingDidEnd)
        tf.addTarget(self, action: #selector(textFiledEdtingEnded), for: .editingDidEndOnExit)
        return tf
    }()
    
    private lazy var segmentedView: JXSegmentedView = {
        let segment = JXSegmentedView()
        segment.dataSource = dataSource
        segment.delegate = self
        return segment
    }()
    
    private lazy var dataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titleNormalFont = .regular(14)
        dataSource.titleNormalColor = .rgba(59, 59, 59, 1)
        dataSource.titleSelectedFont = .medium(15)
        dataSource.titleSelectedColor = .rgba(42, 42, 42, 1)
        return dataSource
    }()
    
    private lazy var tableView: MYGCommunityListView = {
        let listView = MYGCommunityListView(frame: .zero)
        listView.loadDataAction = {[weak self] isRefreshing in
            self?.loadData(isRefreshing: isRefreshing)
        }
        listView.communityListAction = {[weak self] (type, index) in
            switch type {
            case .selected:
                self?.listItemDidSelect(index: index)
            case .like:
                self?.listItemDidClickLike(index: index)
            default: break
            }
            
            
        }
        return listView
    }()
    
    private func listItemDidSelect(index: Int) {
        let listModel = listModels[index]
        let vc = MYGAnswerDetailController()
        vc.communityId = listModel.communities_patient.id
        navigationController?.pushViewController(vc)
    }
    
    private func listItemDidClickCollect(index: Int) {
        let listModel = listModels[index]
        
    }
    
    private func listItemDidClickLike(index: Int) {
        let listModel = listModels[index]
        let likeStatus = listModel.communities_patient.is_like == 0 ? "1" : "0"
        MYGLoading.show(self.view)
    //param: ["id":listModel.communities_patient.id,"like_status":likeStatus,"like_type":"10"
       
        MYGNetwork<MYGCommunityApi, MYGEmptyModel>.request(target: .communitiesLike(type: "10", likeStatus: likeStatus, id: "\(listModel.communities_patient.id)")) { [weak self] item in
               
               guard let self = self else { return }
               MYGLoading.hide(self.view)
   //            guard let response = response else { return }
            if self.listModels[index].communities_patient.is_like == 1 {
                   self.listModels[index].communities_patient.likes = self.listModels[index].communities_patient.likes  - 1
                self.listModels[index].communities_patient.is_like = 0
               } else {
                   self.listModels[index].communities_patient.likes  = self.listModels[index].communities_patient.likes  + 1
                   self.listModels[index].communities_patient.is_like = 1
               }
               self.reloadListView()
               
       } failed: { _, error in
           MYGLoading.hide(self.view)
           MMYGHUD.showToast(text: error)
       }
    }
        
//        MYGNetwork<MYGCommunityApi, MYGEmptyModel>.request(target: .like(type: "20", likeStatus: likeStatus, id: String(listModel.id))) {[weak self] response in
//            guard let self = self else { return }
//            MYGLoading.hide(self.view)
////            guard let response = response else { return }
//            if self.listModels[index].is_like == 1 {
//                self.listModels[index].like_count = self.listModels[index].like_count - 1
//                self.listModels[index].is_like = 0
//            } else {
//                self.listModels[index].like_count = self.listModels[index].like_count + 1
//                self.listModels[index].is_like = 1
//            }
//            self.reloadListView()
//        } failed: {[weak self] _, error in
//            MYGLoading.hide(self?.view)
//            MMYGHUD.showToast(text: error)
//        }
//    }
    
    private func getCommunityType(){
        MYGLoading.show()
    
        MMYGNetwork<MYGCommunityApi,MYGCommunityAllTypeModel>.request(target: .doctor_follow_communities) { [self] tags in
//            MYGLoading.hide()
            guard let items = tags?.data else {return}
            
            contents = items
            dataSource.titles = items.map{$0.name}
            segmentedView.reloadData()
            
            if items.count > 0 {
                communities_id = items.first!.communities_id
                loadData(isRefreshing: true)
            }else {
                MYGLoading.hide()
            }
            
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    
    private func loadData(isRefreshing: Bool) {
        if isRefreshing {
            page = 1
        } else {
            page = page + 1
        }

        MYGLoading.show()
        MMYGNetwork<MYGCommunityApi, MYGPageModel<MYGCommunityListModel>>.request(target: .questionList(communities_id: "\(communities_id)")) {[weak self] response in
            MYGLoading.hide()
            guard let response = response else {
                self?.tableView.endRefreshing(noMoreData: true)
                return
            }
            
            if isRefreshing {
                self?.listModels.removeAll()
            }
            
            self?.listModels.append(contentsOf: response.list)
            self?.tableView.endRefreshing(noMoreData: (self?.listModels.count ?? 0) >= response.page.total)
            self?.reloadListView()
        } failed: {[weak self] _, error in
            MYGLoading.hide()
            self?.tableView.endRefreshing(noMoreData: true)
            MMYGHUD.showToast(text: error)
        }
    }

}

extension MYGAnswerViewViewController {
    
    @objc func reloadMyAnswerData(){
        loadData(isRefreshing: true)
    }
    
    @objc func textFiledEdtingEnded() {
        filterTitle = searchTextFiled.text
        tableView.beginRefreshing()
    }
    
    @objc func navigationMoreAction() {
        let vc = MYGMyAnswerViewController()
        self.navigationController?.pushViewController(vc)
    }
}


extension MYGAnswerViewViewController: JXSegmentedViewDelegate {

    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
       
        communities_id = contents[index].communities_id
        loadData(isRefreshing: true)
    }
}
